<template>
  <div class="app-container">
    <h2>封装的穿梭框选人组件</h2>

    <PersonTransfer :data="mockData" ref="personTransferRef" />

    <div class="submit-area">
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </div>

    <div v-if="submittedData" class="result-display">
      <h3>提交的人员信息:</h3>
      <pre>{{ JSON.stringify(submittedData, null, 2) }}</pre>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import PersonTransfer from "../components/PersonTransfer.vue"; // 确保路径正确
import { ElMessage } from "element-plus";

// 定义 User 接口，以便 submittedData 有正确的类型
interface User {
  userId: string;
  userName: string;
  age: number;
  gender: string;
}

// ★ 步骤1: 创建一个 ref 来持有子组件实例
const personTransferRef = ref<InstanceType<typeof PersonTransfer> | null>(null);

// 用于存储提交后获取的数据
const submittedData = ref<User[] | null>(null);

// 模拟的原始数据
const mockData = ref([
  {
    dept: "二部",
    deptId: "1002",
    children: [
      { userId: "01", userName: "小李", age: 25, gender: "男" },
      { userId: "02", userName: "小张", age: 21, gender: "女" },
      { userId: "03", userName: "小南", age: 19, gender: "男" },
    ],
  },
  {
    dept: "三部",
    deptId: "1003",
    children: [
      { userId: "15", userName: "老周", age: 35, gender: "男" },
      { userId: "59", userName: "小蒋", age: 21, gender: "女" },
    ],
  },
  {
    dept: "市场部",
    deptId: "1005",
    children: [{ userId: "77", userName: "王五", age: 28, gender: "男" }],
  },
]);

/**
 * ★ 步骤4: 提交按钮的点击事件处理函数
 */
const handleSubmit = () => {
  if (personTransferRef.value) {
    // 通过 ref.value 调用子组件暴露的 getSelectedData 方法
    const selectedUsers = personTransferRef.value.getSelectedData();

    console.log("从子组件获取到的人员信息:", selectedUsers);

    if (selectedUsers.length === 0) {
      ElMessage.warning("请至少选择一位人员！");
      return;
    }

    // 将获取到的数据存起来，以便在模板中展示
    submittedData.value = selectedUsers;
    ElMessage.success("提交成功！");
  } else {
    console.error("无法获取到 PersonTransfer 组件实例");
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  font-family: sans-serif;
}
.submit-area {
  margin-top: 20px;
  text-align: center;
}
.result-display {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border: 1px dashed #e0e0e0;
  border-radius: 4px;
}
.result-display h3 {
  margin-top: 0;
}
pre {
  font-family: "Courier New", Courier, monospace;
  font-size: 14px;
  color: #333;
}
</style>
